#include <Arduino.h>
#include <timer-api.h>
#include "packet.hpp"

uint16_t a = 0, b = 0;
unsigned char temp;
unsigned char res0 = 5;
unsigned char res1 = 5;
unsigned char res2 = 5;
unsigned char *prt_char;




packet p1;
MsgDemo_output_msg msg;
MsgDemo_output_header * hdr;

void setup()
{
  Serial.begin(115200);
  // adc0
  pinMode(PC0, INPUT);
  // adc1
  pinMode(PC1, INPUT);
  // adc2
  pinMode(PC2, INPUT);

  // timer_init_ISR_100KHz(TIMER_DEFAULT);
  timer_init_ISR_1KHz(TIMER_DEFAULT);
  // инициализация Timer1
  sei();                   // включить глобальные прерывания
  p1.header.numPac =0;
  p1.header.frameNumbers=1;
  p1.header.totalPacketLen = sizeof(MsgDemo_output_msg);
  hdr = &p1.header;
  
}

void loop()
{
  unsigned char res_copy0,res_copy1,res_copy2;
  p1.header.numPac++;
 
  noInterrupts();
  msg = p1.setFrame(res0,res1,res2);
  interrupts();

  if (p1.message.data[0] > 20 or p1.message.data[1] >20 or p1.message.data[2] >20)
  {
    /* code */
    // Serial.println("----------------------------");
    // Serial.write(res_copy0);
    // Serial.write(res_copy1);
    // Serial.write(res_copy2);
    noInterrupts();
    res0 = 0;
    res1 = 0;
    res2 = 0;
    interrupts();
  }
  p1.header.timeStamp = millis();
  msg.header.tag =1; //tag =1
  msg.header.len =sizeof(MsgDemo_output_msg) -sizeof(MsgTLV);

  Serial.write((char *) hdr,sizeof(MsgDemo_output_header));
  Serial.write((char *) &msg,sizeof(MsgDemo_output_msg));
  p1.header.numPac =0;
  // сделай цикл
  

  delay(200);
}

void timer_handle_interrupts(int timer)
{

  temp = analogRead(PC0);
  if (temp >= res0)
  {
    res0 = temp;
  }
    temp = analogRead(PC1);
  if (temp >= res1)
  {
    res1 = temp;
  }
  temp = analogRead(PC2);
  if (temp >= res2)
  {
    res2 = temp;
  }
}